<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Notifications\FindPassword;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Notification;

class PasswordContoller extends Controller
{
    // 显示视图
    public function index()
    {
        return view('password.index');
    }

    // 发送邮件
    public function sendemail(Request $request)
    {
        $this->validate($request, [

            'email' => 'required|min:3|email'
        ]);

        $user = User::where('email', $request->email)->first();
        if (!$user) {
            session()->flash('danger', '该邮箱没有注册用户，请重试其他邮箱');
            return redirect()->route('findpassword');
        }
        Notification::send($user, new FindPassword($user->email_token));
        session()->flash('success', '邮件发送成功！');
        return redirect()->route('findpassword');
    }


    //显示重置页面
    public function findpasswordstore(Request $request)
    {
        $token = $request->token;
        $user = User::where('email_token', $token)->first();
        return view('password.password', compact('user', 'token'));
    }

    //提交修改密码
    public function setpassword(Request $request)
    {
        $this->validate($request, [
            'password' => 'required|min:4|confirmed'
        ]);

        $user = User::where('email_token', $request->token)->first();
        $user->password = bcrypt($request->password);
        $user->save();
        session()->flash('success', '密码修改成功');
        return redirect()->route('login');
    }
}
